﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Data.Linq;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ServisniList.Core;

namespace ServisniList
{
    public partial class Djelatnici : Form
    {

        #region Fields

        private DataModelDataContext context = null;

        #endregion

        #region Constructor

        public Djelatnici()
        {
            InitializeComponent();
        }

        #endregion

        #region Event handlers

        private void Korisnici_Load(object sender, EventArgs e)
        {
            context = new DataModelDataContext(ConfigurationManager.ConnectionStrings["ServisniListConnectionString"].ConnectionString);
            djelatnikBindingSource.DataSource = context.Djelatniks.ToList();
        }

        private void Djelatnici_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (context != null)
            {
                context.Dispose();
            }
        }

        private void btnSnimi_Click(object sender, EventArgs e)
        {
            this.Update();
            context.SubmitChanges();
        }

        private void dgvDjelatnici_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            DataGridViewCell cell = ((DataGridView)sender).CurrentCell;
            if (cell is DataGridViewCheckBoxCell)
            {
                if (cell.OwningColumn.Name.Equals("Deaktiviraj"))
                {
                    DataGridViewRow red = ((DataGridView)sender).CurrentRow;
                    Djelatnik editiraniDjelatnik = red.DataBoundItem as Djelatnik;
                    if (editiraniDjelatnik.Deaktiviraj)
                    {
                        editiraniDjelatnik.DatumDeaktivacije = DateTime.Now;
                    }
                    else
                    {
                        editiraniDjelatnik.DatumDeaktivacije = null;
                    }
                }
            }
        }

        private void btnDodajNovogDjelatnika_Click(object sender, EventArgs e)
        {
            DjelatnikNovi noviDjelatnik = new DjelatnikNovi();
            noviDjelatnik.ShowDialog();

            if (noviDjelatnik.UspjesnoKreiranNovi)
            {
                djelatnikBindingSource.DataSource = context.Djelatniks.ToList();
            }
        }

        protected override void OnKeyDown(KeyEventArgs e)
        {
            base.OnKeyDown(e);
            if (e.KeyCode == Keys.Escape)
                this.Close();
        }

        #endregion
    
    }
}
